import React, { useState, useEffect } from 'react';
import { useEffectOnce } from 'react-use';
import kls from 'classnames';
import { connect } from 'umi';
import { CloseOutlined, UploadOutlined } from '@ant-design/icons';
import { Form, Input, Select, Upload, Button } from 'antd';
import _ from 'lodash';
import styles from './index.less';
const types = ['名称', '进度', '说明', '附件', '按钮'];
const scheduleOption = [
  {
    value: 'noStart',
    label: '未拆迁',
  },
  {
    value: 'underway',
    label: '拆迁中',
  },
  {
    value: 'fulfill',
    label: '已拆迁',
  },
];
const SchemeForm = ({ dispatch, isVisibleGraph, sketchViewModel }) => {
  const [formData, setFormData] = useState<any>({
    name: '',
    schedule: 'noStart',
    explain: '',
    fileList: [],
    revamp: false,
  });
  // 关闭弹框
  function CloseGraphPopup() {
    dispatch({
      type: 'scheme/updateIsVisibleGraph',
      payload: false,
    });
  }
  // 获取input内容
  const handleInputChange = (value, key) => {
    setFormData(prevFormData => ({
      ...prevFormData,
      [key]: value,
    }));
  };
  // Select选择
  function handleChange(e) {
    // 等待处理
    setFormData(prevFormData => ({
      ...prevFormData,
      schedule: e,
    }));
  }
  // 文件上传
  function handleUpload(info) {
    let fileList = [...info.fileList];
    // fileList = fileList.slice(-1); // 只保留最新上传的文件，如果要保留多个文件，请注释此行代码
    setFormData(prevFormData => ({
      ...prevFormData,
      fileList: fileList,
    }));
  }
  // 防抖函数
  const debouncedGetData = _.debounce(handleFormSubmit, 500);
  // 清空表单数据
  function handleFormReset() {
    setFormData({
      name: '',
      schedule: 'noStart',
      explain: '',
      fileList: [],
      revamp: false,
    });
  }
  // 处理表单提交
  function handleFormSubmit() {
    console.log('处理表单提交', formData);
    dispatch({
      type: 'scheme/updateIsVisibleGraph',
      payload: false,
    });
    formData.revamp = true;
    localStorage.setItem('particulars', JSON.stringify(formData));
    sketchViewModel.complete();
    handleFormReset();
  }
  useEffect(() => {
    if (!isVisibleGraph) {
      console.log('isVisibleGraph是', isVisibleGraph);
    } else {
      console.log('执行了吗');
      let data = JSON.parse(localStorage.getItem('particulars') || '{}');
      if (JSON.stringify(data) !== '{}') {
        setFormData(data);
      }
    }
  }, [isVisibleGraph]);

  // 获取不同状态的内容
  function getDiverseContent(state) {
    const { name, schedule, explain, fileList } = formData;
    switch (state) {
      case '名称':
        return (
          <Form.Item>
            <Input
              value={name}
              onChange={e => handleInputChange(e.target.value, 'name')}
              placeholder="请输入名称"
            />
          </Form.Item>
        );
      case '进度':
        return (
          <Form.Item>
            <Select
              value={schedule}
              style={{ width: '110px' }}
              onChange={handleChange}
              options={scheduleOption}
            />
          </Form.Item>
        );
      case '说明':
        return (
          <Form.Item>
            <Input.TextArea
              value={explain}
              onChange={e => handleInputChange(e.target.value, 'explain')}
              rows={1}
              placeholder="请输入说明"
            />
          </Form.Item>
        );
      case '附件':
        return (
          <Form.Item>
            <Upload onChange={handleUpload} fileList={fileList}>
              <Button icon={<UploadOutlined />}>上传附件</Button>
            </Upload>
          </Form.Item>
        );
      case '按钮':
        return (
          <Form.Item>
            <Button onClick={debouncedGetData} type="primary" htmlType="submit">
              提交
            </Button>
            <Button onClick={handleFormReset} style={{ marginLeft: 20 }} htmlType="reset">
              重置
            </Button>
          </Form.Item>
        );
      default:
        break;
    }
  }
  return (
    <>
      <div className={kls(styles.graphInfo)}>
        <div
          className={styles.basePanel}
          style={
            isVisibleGraph
              ? { visibility: 'visible', marginBottom: 20 }
              : {
                  height: 0,
                  border: 0,
                  marginBottom: 0,
                  visibility: 'hidden',
                }
          }
        >
          <div className={styles.basePanelTitle}>
            {/* 构件浮窗 */}
            <span className={styles.graphInfoTitle} title="征拆详情">
              征拆详情
            </span>
            <CloseOutlined
              style={{ float: 'right', margin: '14px 16px 0 0' }}
              className="custom-panel-title-close"
              onClick={CloseGraphPopup}
            />
          </div>
          <div className={styles.graphInfoBox}>
            {types.map(i => {
              return (
                <div className={styles.graphInfoBody}>
                  <div className={styles.graphInfoBodyTitle}> {i}</div>
                  <Form initialValues={formData} className={styles.graphInfoBodyContent}>
                    {getDiverseContent(i)}
                  </Form>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </>
  );
};

export default connect(({ scheme }) => {
  return {
    isVisibleGraph: scheme.isVisibleGraph,
    sketchViewModel: scheme.sketchViewModel,
  };
})(React.memo(SchemeForm));
